package com.sheepone.util;

import java.lang.reflect.Constructor;
import java.util.Collection;

/**
 * @author Miss.杨
 * @description
 * @since 2024/3/2 - 22:09
 */
@SuppressWarnings("unchecked")
public class ClassUtil {
    private ClassUtil() {
    }

    public static <T> Class<T> getComponentType(T[] clazz) {
        return (Class<T>) clazz.getClass().getComponentType();
    }

    public static <T> Class<T> getComponentType(Collection<T> collection) {
        if (collection.isEmpty()) {
            throw new RuntimeException("collection is empty");
        }
        return (Class<T>) collection.iterator().next().getClass();
    }

    public static <T> Constructor<T> getConstructor(Class<T> clazz, Class<?>... parameterTypes) {
        try {
            return clazz.getDeclaredConstructor(parameterTypes);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T getInstance(Class<T> clazz, Class<?>... parameterTypes) {
        return getInstance(true, clazz, parameterTypes);
    }
   
    public static <T> T getInstance(boolean throwable, Class<T> clazz, Class<?>... parameterTypes) {
        T instance = null;
        try {
            Constructor<?> constructor = getConstructor(clazz, parameterTypes);
            constructor.setAccessible(true);
            return (T) constructor.newInstance();
        } catch (Exception e) {
            if (throwable) {
                throw new RuntimeException(e);
            }
        }
        return instance;
    }
}
